//
//  JiZhenViewController.m
//  安好
//
//  Created by rlp on 14-12-9.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "JiZhenViewController.h"

#import "ZhengZhuangViewController.h"
#import "SelfInspectionViewController.h"
#import "MyChineseBookAddress.h"

// 区分模拟器和真机
#if TARGET_IPHONE_SIMULATOR
#define SIMULATOR 1
#elif TARGET_OS_IPHONE
#define SIMULATOR 0
#endif
@interface JiZhenViewController () 

@end

@implementation JiZhenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    dataSouceArray = [NSMutableArray array];

    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout=UIRectEdgeNone;

    [self makeNavBarView];
    [self makeTableView];
    [self loadJizhenList];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - 设置导航条
-(void)makeNavBarView
{
//    self.title = @"科室自查";
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClicked:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    
    
    
    if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[ZhengZhuangViewController class]]) {
        UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
        [rightButton setTitle:@"图文" forState:UIControlStateNormal];
        rightButton.titleLabel.font = [UIFont systemFontOfSize:BUTTON_TEXTLABEL_FOUNT_SIZE];
        [rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [rightButton sizeToFit];
        UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    }else{
    
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
    [rightButton setTitle:@"直拨120" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:BUTTON_TEXTLABEL_FOUNT_SIZE];
    [rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton sizeToFit];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    }
    
    

    
}

-(void)leftButtonClicked:(UIButton *)sender
{

    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)rightButtonClicked:(UIButton *)sender{
    if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[ZhengZhuangViewController class]]) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        if (SIMULATOR==1) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的设备暂不支持电话功能!" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
            [alert show];
            return;
            
        }
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt:120"]];
    }
}
#pragma mark - 创建tableView 设置table的代理、添加头视图横线
-(void)makeTableView
{
    self.m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    [self.view addSubview:self.m_tableView];
    self.m_tableView.delegate = self;
    self.m_tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.m_tableView.showsHorizontalScrollIndicator = NO;
    self.m_tableView.showsVerticalScrollIndicator = NO;
    self.m_tableView.sectionIndexColor= [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];

    [self.m_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //    //创建头视图 - 一条线
    //    self.headerLineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.5)];
    //    self.headerLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
    //    self.tableView.tableHeaderView = self.headerLineView;
}
#pragma mark - 获取急诊的疾病列表
- (void)loadJizhenList
{
    
    
    
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,self.appendingString] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
        MyNSLog("%@",responseObject);
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];//失败
        }else{
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                
                NSArray *allkeys = [responseObject objectForKey:@"data"];
                
                
                for (int index = 0;index < allkeys.count; index++)
                {
                    //如果是症状自查把name 和 id 保存
                    if([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[ZhengZhuangViewController class]])
                    {
                        NSDictionary *sub = [allkeys objectAtIndex:index];
                        
                        NSString * value = [sub objectForKey:@"symptomid"];
                        NSString * key = [sub objectForKey:@"symptomname"];
                        
                        //把emeid 存到沙盒，下一个界面用
                        NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:value forKey:key];
                        
                        [dataSouceArray addObject:[sub objectForKey:@"symptomname"]];
                    }
                    else  if([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[SelfInspectionViewController class]])//如果是急诊自查把name 和 id 保存
                    {
                        NSDictionary *sub = [allkeys objectAtIndex:index];
                        
                        NSString * value = [sub objectForKey:@"emeid"];
                        NSString * key = [sub objectForKey:@"eme"];
                        
                        //把emeid 存到沙盒，下一个界面用
                        NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:value forKey:key];
                        
                        [dataSouceArray addObject:[sub objectForKey:@"eme"]];
                    }
                }
                
                
                self.m_allName = [[NSMutableArray alloc] init];
                for (int i=0; i<dataSouceArray.count; i++) {
                    
                    if ([[dataSouceArray objectAtIndex:i] canBeConvertedToEncoding:NSASCIIStringEncoding]) {
                        
                        [self.m_allName addObject:[NSString stringWithFormat:@"%c", [[dataSouceArray objectAtIndex:i] characterAtIndex:0]]];
                        
                    }else{
                        char firstChar = pinyinFirstLetter([[dataSouceArray objectAtIndex:i] characterAtIndex:0]);
                        NSString *youName = [NSString stringWithFormat:@"%c",firstChar];
                        //不添加重复元素
                        if (![self.m_allName containsObject:[youName uppercaseString]]) {
                            [self.m_allName addObject:[youName uppercaseString]];
                        }
                        
                    }
                    
                }
                
                
                [self.m_allName sortUsingSelector:@selector(compare:)];
                //
                nameDic = [[NSMutableDictionary alloc] init];
                //每个section对应的行数列表
                for(NSString * sectionString  in self.m_allName)
                {
                    NSMutableArray *rowSource = [[NSMutableArray alloc] init];
                    
                    for (NSString *charString in dataSouceArray) {
                        
                        char firstchar;
                        
                        if ([charString canBeConvertedToEncoding:NSASCIIStringEncoding]){
                            
                            firstchar = [charString characterAtIndex:0];
                        }else{
                            
                            firstchar = pinyinFirstLetter([charString characterAtIndex:0]);
                        }
                        NSString *youName = [NSString stringWithFormat:@"%c",firstchar];
                        if ([sectionString isEqualToString:[youName uppercaseString]]) {
                            [rowSource addObject:charString];
                        }
                        
                    }
                    
                    [nameDic setValue:rowSource forKey:sectionString];
                    
                }
                
                [self.m_tableView reloadData];
            }else{
                [self showCustomHudSingleLine:@"网络数据格式错误"];
            }
            
        }
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        
    }];

 
}

#pragma mark - UITableView DataSource & Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.m_allName count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *dicCount = [nameDic objectForKey:[self.m_allName objectAtIndex:section]];
    return [dicCount count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ((kScreenWidth == 414) ? 44*1.2 : 44);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    NSString * sectionString = [self.m_allName objectAtIndex:indexPath.section];
    
    NSArray *allShowName = [nameDic objectForKey:sectionString];
    if (allShowName.count>0) {
        cell.textLabel.text = [allShowName objectAtIndex:indexPath.row];
    }
    
    cell.textLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT];
    
    /**
     *  线条的处理
     */
    
    UIView *bottomLineView = [[UIView alloc]initWithFrame:CGRectMake(5, ((kScreenWidth == 414) ? 44*1.2 : 44)-0.5,kScreenWidth-5, 0.5)];

    
    bottomLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
    [cell addSubview:bottomLineView];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark -

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self.m_allName objectAtIndex:section];
}


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
    
    for(char c = 'A';c<='Z';c++)
        
        [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    
    return toBeReturned;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    
    
    NSInteger count = 0;
    
    for(NSString *character in self.m_allName)
    {
        
        if([character isEqualToString:title]) return count;
        count ++;
        
        
    }
    
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    
    if([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[ZhengZhuangViewController class]])//症状自查需要跳转的页面
    {
        QuestionViewController *question = [[QuestionViewController alloc] init];
        NSString * sectionString = [self.m_allName objectAtIndex:indexPath.section];
        NSArray *allShowName = [nameDic objectForKey:sectionString];
        
        if (allShowName.count>0) {
            question.symptomname = TextString([allShowName objectAtIndex:indexPath.row]);
            NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
            question.symptomid = [userDefaults objectForKey:[allShowName objectAtIndex:indexPath.row]];
        }
        
        [self.navigationController pushViewController:question animated:YES];

    }
    else  if([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2] isKindOfClass:[SelfInspectionViewController class]])//如果是急诊自查把name 和 id 保存
    {
        JiZhenDetailViewController *jizhenDetail = [[JiZhenDetailViewController alloc] init];
        NSString * sectionString = [self.m_allName objectAtIndex:indexPath.section];
        NSArray *allShowName = [nameDic objectForKey:sectionString];
        
        if (allShowName.count>0) {
            jizhenDetail.emeName = TextString([allShowName objectAtIndex:indexPath.row]);
            NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
            jizhenDetail.emeId = [userDefaults objectForKey:[allShowName objectAtIndex:indexPath.row]];
        }
        
        [self.navigationController pushViewController:jizhenDetail animated:YES];
    }
    
    
}


@end
